import store from "/store/index.js";
// api URL
let apiGateway = store.state.gateway;
// 封装微信请求方法
// params:接口入参
// hasCatch:用户逻辑主动捕获异常，此处不处理只抛出
let lastTime = 0;
const request = async (params, hasCatch) => {
	store.commit('showLoading');
	// 登录鉴权验证
	let token = uni.getStorageSync('login').token || "";

	apiGateway = params.gateway || apiGateway;

	// api起飞
	let header = {
		"Content-Type": "application/json"
	};
	let method = params.method;
	// let url = `${params.url}${params.url.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
	let url = `${params.url}`;
	let data = {
		...params.data
	}
	console.log("request url ===> ", url);
	console.log("request data ===> ", data);
	let needTime = 0;
	if (apiGateway.indexOf('mxnzp') >= 0) {
		// 节流（mxnzp免费api的QPS只有1）
		const nowTime = new Date().getTime();
		const remainTime = nowTime - lastTime;
		const needTimeout = 1200 - remainTime;
		needTime = needTimeout > 0 ? needTimeout : 0;
	}
	console.log("request needTime ===> ", needTime);
	return new Promise((resolve, reject) => {

		setTimeout(() => {
			if (apiGateway.indexOf('mxnzp') >= 0) {
				lastTime = new Date().getTime();
			}
			uni.request({
				url: apiGateway + url, // api url
				data: data, // 请求参数
				method: method, // get/post
				header: header, // 头部
				success(res) {
					// 请求成功
					console.log("request success res ===> ", JSON.stringify(res));
					// 判断状态码---errCode状态根据后端定义来判断
					if (res.statusCode === 200) {
						if (hasCatch) {
							resolve(res.data);
						} else if (res.data.code === 200) {
							resolve(res.data.result);
						} else if (res.data.code === 1) {
							resolve(res.data.data);
						} else if (res.data.status === '1') {
							resolve(res.data);
						} else {
							reject(res);
						}
					} else {
						reject(res);
					}
				},
				fail(err) {
					// 判断状态码---errCode状态根据后端定义来判断
					setTimeout(() => {
						reject(err);
					});
				},
				complete() {
					console.log("request complete ===> ");
					setTimeout(() => store.commit('hideLoading'), 500);
				},
			});
		}, needTime);

	}).then((res) => {
		console.log("then res ===> ", JSON.stringify(res));
		return res;
	}).catch((err) => {
		console.log("catch err ===> ", JSON.stringify(err));
		if (hasCatch) {
			return err;
		} else {
			showErr(err);
		}
	});
};

const showErr = (e) => {
	if (e) {
		// 统一处理状态码
		// success: 显示成功图标，error: 显示错误图标； fail: 显示错误图标，此时title文本无长度显示； exception: 显示异常图标，此时title文本无长度显示； loading: 显示加载图标；none: 不显示图标。注意：有平台差异
		// 目前大致是0：正常，400：参数错误，401：系统网络错误，402：权限不正确(不一定准确)
		setTimeout(() => {
			if (e.statusCode && e.statusCode < 400) {
				switch (e.statusCode) {
					case 200:
						uni.showToast({
							title: e.data.msg || "参数错误！",
							icon: "none",
							duration: 3000,
						});
						break;
					default:
						uni.showToast({
							title: e.data.msg || "未知错误！",
							icon: "error"
						});
						break;
				}
			} else if (e.statusCode === 400) {
				uni.showToast({
					title: e.data.msg || "参数错误！",
					icon: "none"
				});
			} else if (e.statusCode === 401) {
				uni.showToast({
					title: e.data.msg || "登录失效！",
					icon: "none"
				});
				// 登錄失效
				store.commit('login/clearLoginInfo');
				setTimeout(() => {
					uni.reLaunch({
						url: "/pages/auth/login/index"
					});
				}, 1000);
			} else if (e.errMsg && e.errMsg.indexOf('request:fail') !== -1) {
				uni.showToast({
					title: e.data.msg || "网络异常！",
					icon: "error"
				});
			} else {
				uni.showToast({
					title: e.data.msg || "未知异常！",
					icon: "error"
				});
			}

		})
	}
}

export {
	apiGateway,
	request,
}